package henry.lucky.alphay;

import henry.lucky.alphay.Domain.Card;
import henry.lucky.alphay.Domain.Prize;
import henry.lucky.alphay.Domain.PrizeCard;
import henry.lucky.alphay.db.DataBase;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class LuckyDraw{

	private int cols;
	private int groupCount;
	private int LuckyCount;
	private Timer timer;
	private static JLabel labelTimer;
	private static List<Card> cards;
	private boolean canLucky=true; 
	private Prize prize;
	private List<Integer> everyLuckyNum;
	private int currentCompleteCount=0;
	private List<Prize> prizes;
	private JTextArea area;
	private JLabel labelPrize;
	private Font f;
	private DataBase dataBase=new DataBase();
	private List<Card> initCard(){
		
		return dataBase.findCardsByCanType(0);
	}
	private List<Prize> initPrize(){
		
		return dataBase.findCurrentLuckyPrize();
	}
	public void showFrame(){
		try {
			UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
		} catch (ClassNotFoundException | InstantiationException
				| IllegalAccessException | UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cards=initCard();
		prizes =initPrize();
//		insertPrize();
		//界面及界面元素生成
		JFrame frame=new JFrame("抽奖");
		Container container=frame.getContentPane();
		JPanel panel=new JPanel();
		JPanel paneldown=new JPanel();	
		JPanel panelTop=new JPanel();
		JPanel panelNorth=new JPanel(new BorderLayout());
		container.add("North",panelTop);
		container.add("Center",panel);
		container.add("South", paneldown);
		//设置标题
		JLabel label=new JLabel("抽奖",JLabel.CENTER);
		JLabel labeltitle=new JLabel("抽奖结果",JLabel.CENTER);
		labelPrize=new JLabel("", JLabel.CENTER);
		area=new JTextArea();
		Font font=new Font("title", Font.CENTER_BASELINE, 40);
		Font font1=new Font("title", Font.CENTER_BASELINE, 30);
		f=new Font("content", Font.CENTER_BASELINE, 500);
		label.setFont(font);
		labeltitle.setFont(font1);
		labelPrize.setFont(font1);
		area.setFont(f);
		//设置按钮
		JButton nextButton=new JButton("下一个奖项");
		labelTimer=new JLabel();
		Font fontTimer=new Font("title", Font.CENTER_BASELINE, 25);
		labelTimer.setFont(fontTimer);
		JButton addButton=new JButton("补抽");
		JButton button=new JButton("抽奖");
		button.setBackground(new Color(255,0,0));
		JButton settingsPrizeButton=new JButton("奖项设置");
		JButton settingsCardButton=new JButton("奖券设置");
		JButton resultButton=new JButton("抽奖结果查询");		
		//添加中奖的列表
		FlowLayout downLayout=new FlowLayout(FlowLayout.CENTER,60,10);
		panelNorth.add(labeltitle,BorderLayout.NORTH);
		panelNorth.add(labelPrize,BorderLayout.SOUTH);
		paneldown.setLayout(downLayout);
		panelTop.add(label);
		panel.setLayout(new BorderLayout());
		panel.add(new JScrollPane(area),BorderLayout.CENTER);
		panel.add(panelNorth,BorderLayout.NORTH);
		paneldown.add(nextButton);
		paneldown.add(labelTimer);
		paneldown.add(button);
		paneldown.add(addButton);
		paneldown.add(settingsCardButton);
		paneldown.add(settingsPrizeButton);
		paneldown.add(resultButton);
		timer=new Timer(200, new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				int intRd =(int)(Math.round(Math.random()*(cards.size()-1)));
				labelTimer.setText(cards.get(intRd).getCardName());
			}
		});
		timer.start();
		prize=LuckyItem();
		if(prize==null){
			canLucky=false;
			JOptionPane.showMessageDialog(null, "所有奖项已经抽完");
		}else{
			initLucky();
		}	
		button.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if(canLucky){
					
					new MyLuckyThread().start();
				}else{
					JOptionPane.showMessageDialog(null, "这个奖项已经抽完");
				}
				
			}
		});
		addButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if(canLucky){
					JOptionPane.showMessageDialog(null, "这个奖项还没有抽完不需要补抽");
				}else{
					timer.restart();
					Card card=Lucky();
					String resultStr=area.getText()+"\n\r";
					area.setText(resultStr+card.getCardName());
					timer.stop();
				}

			}
			
		});
		nextButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				prizes=dataBase.findCurrentLuckyPrize();
				prize=LuckyItem();
				area.setText("");
				if(prize==null){
					canLucky=false;
					JOptionPane.showMessageDialog(null, "所有奖项已经抽完");
				}else{
					timer.restart();
					initLucky();
				}	
			}
		});
		settingsCardButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				new CardSetting().show();
			}
		});
		
		settingsPrizeButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				Settings setting=new Settings();
				setting.showSettings();
			}
		});
		resultButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				ResultLucky resultLucky=new ResultLucky();
				resultLucky.showFrame();
			}
		});
		frame.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosed(WindowEvent e) {
				// TODO Auto-generated method stub
				super.windowClosed(e);
				timer.stop();
				System.exit(0);
			}
		});
		frame.setSize(1024, 768);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	//设置界面各项初始状态
	protected void initLucky() {
		
//		currentCols=0;
		everyLuckyNum=getLuckyNumber(prize.getNumber(),prize.getCycleIndex());
//		everyColNum=getLuckyNumber(prize.getNumber(), 10);
//		everyColNum=setFontRowCount(number)
//		cols=everyColNum.get(currentCols);
		groupCount=1;
		labelPrize.setText("奖项："+prize.getPrizeName()+",  奖品："+prize.getName()+",  奖项数量:"+prize.getNumber()+",  抽奖次数："+prize.getCycleIndex());
		canLucky=true;
		currentCompleteCount=0;
		if(prize.getNumber()<prize.getCycleIndex()){
			LuckyCount=prize.getNumber();
		}else{
			LuckyCount=prize.getCycleIndex();
		}
		if(LuckyCount<1){
			LuckyCount=1;
		} 
	}
	//根据所要显示的数量设置areaText字体和行数
	private int setFontRowCount(int number){
		
		if(number>20){
			f=new Font("area", Font.CENTER_BASELINE, 60);
			return 6;
		}else if(number>9){
			f=new Font("area", Font.CENTER_BASELINE, 90);
			return 4;
		}else if(number>4){
			f=new Font("area", Font.CENTER_BASELINE, 140);
			return 3;
		}else if(number>1){
			f=new Font("area", Font.CENTER_BASELINE, 200);
			return 2;
		}else if(number>0){
			f=new Font("area", Font.CENTER_BASELINE, 500);
			return 1;
		}
		return 0;
	}
	//根据抽奖数量和抽奖次数生成一个每次抽奖的数量的集合
	private List<Integer> getLuckyNumber(int number, int cycleIndex) {
		
		List<Integer> integers=new ArrayList<>();
		int everyInt;//每次抽奖数量（需要通过下面的变量修正）
		int addOneInt=0;//需要加1的数量
		if(cycleIndex>=number){
			everyInt=1;
		}else{
			everyInt=number/cycleIndex;
			addOneInt=number%cycleIndex;			
		}
		for(int i=0;i<addOneInt;i++){
			integers.add(everyInt+1);
		}
		for(int i=addOneInt;i<cycleIndex;i++){
			integers.add(everyInt);
		}
		return integers;
	}
	private Prize LuckyItem(){
		
		Prize prizeResult=null;
		for(Prize prize:prizes){
			if(prize.getCanType()==0){
				if(prizeResult==null){
					prizeResult=prize;
				}else{
					if(prize.getLuckyIndex()>prizeResult.getLuckyIndex()){
						prizeResult=prize;
					}
				}				
			}
		}
		return prizeResult;
	}
	private Card Lucky(){
		Card card = new Card("");
		int intRd =(int)(Math.round(Math.random()*(cards.size()-1)));
		card=cards.get(intRd);
		PrizeCard prizeCard=new PrizeCard(card.getCardName(), prize.getPrizeName());
		card.setIsLuckied(1);
		cards.remove(intRd);
		dataBase.updateCard(card);					
		dataBase.insertPrizeCard(prizeCard);
		labelTimer.setText(cards.get(intRd).getCardName());
		return card;
	}
	private class MyLuckyThread extends Thread{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			labelPrize.setText("奖项："+prize.getPrizeName()+",  奖品："+prize.getName()+",  奖项数量:"+prize.getNumber()+",  抽奖次数："+prize.getCycleIndex());
			labelPrize.setText(labelPrize.getText()+"第"+groupCount+"组");
			int number=everyLuckyNum.get(currentCompleteCount);
			int colCount=setFontRowCount(number);
			cols=colCount;
//			String resultStr=area.getText();
			Card card = new Card("");
			String resultStr="";
			area.setFont(f);
			for(int i=0;i<number;i++){
				
				card=Lucky();
				if(cols>1){
					resultStr=resultStr+card.getCardName()+" | ";
					cols--;								
				}
				else{
					resultStr=resultStr+card.getCardName()+"\r\n";
//					currentCols++;
					cols=colCount;			
				}			
				try {
					sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				area.setText(resultStr);
			}			
			LuckyCount--;
			groupCount++;
			if(LuckyCount==0){
				
				timer.stop();
				labelTimer.setText(card.getCardName());
				prize.setCanType(1);
				dataBase.updatePrize(prize);
				canLucky=false;
//				JOptionPane.showMessageDialog(null, prize.getPrizeName()+"抽奖结束");
			}
			super.run();
		}
	}
}
